<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 二叉树实现结构
        function Node(value) {
            this.value = value;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(null)
        var c = new Node(2)
        var d = new Node(3)
        a.left = b
        a.right = c
        b.left = d
        // 前序遍历-迭代法
        var preorderTraversal = function (root) {
            if (!root) return []
            let stack = []
            // 根节点先放进去
            stack.push(root)
            let res = []
            // 栈不为空
            while (stack.length) {
                // 弹出节点，放到栈中
                let cur = stack.pop()
                res.push(cur.value)
                // 右节点入栈
                cur.right && stack.push(cur.right)
                // 左节点入栈
                cur.left && stack.push(cur.left)
            }
            return res
        }
        console.log(preorderTraversal(a));



    </script>
</body>

</html>